// Package controllers
// @Title  base.go
// @Description  基类控制器
// @Author  小斌 (时间 格式是2021/12/02  11:40)
// @Update  小斌 (时间 格式是2021/12/02  11:40)

package controllers

import (
	"beego-admin/service"
	"encoding/json"
	"github.com/astaxie/beego"
)

type BaseController struct {
	beego.Controller
	controllerName string
	actionName     string
}

type ReturnJson struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

type ReturnLayuiJson struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Total int 		 `json:"count"`
	Data interface{} `json:"data"`
}

func (this *BaseController) Prepare() {
	this.checkLogin()
	this.checkMenuAuth()
}

func (this *BaseController) checkLogin()  {
	userId := this.GetSession("user_id")
	if userId == nil{
		this.Redirect("/admin/login", 302)
	}
}

func (this *BaseController) checkMenuAuth()  {
	controllerName,actionName := this.GetControllerAndAction()
	authControllerJson := this.GetSession("auth_controller_json")
	roleId := this.GetSession("role_id")

	bool := service.CheckMenuAuth(controllerName,actionName,authControllerJson.(string),roleId.(int))
	if !bool{
		this.Data["json"] = this.AjaxReturn(20001,"无权限访问",nil)
		this.ServeJSON()
		this.StopRun()
	}

	JsonRes := make(map[string]int)
	_ = json.Unmarshal([]byte(authControllerJson.(string)), &JsonRes)

	this.Data["button_map"] = JsonRes
}

func (this *BaseController) AjaxReturn(code int, msg string, data interface{}) *ReturnJson {
	return &ReturnJson{Code: code, Msg: msg, Data: data}
}

func (this *BaseController) AjaxLayuiTableReturn(code int, msg string,total int, data interface{}) *ReturnLayuiJson {
	return &ReturnLayuiJson{Code: code, Msg: msg,Total: total, Data: data}
}

